const router = require('koa-router')();
const fs = require("fs");
const path = require("path");

const {
  readFile,
  writeFile
} = require("../common/js/index");

router.get('/', async (ctx, next) => {
  await ctx.render('index')
})

router.get('/getMaterialList', async (ctx, next) => {
  const type=ctx.request.query.type;
  const jsonData = readFile();
  const data = jsonData.filter(item => {
    return (item["料盘"] && item["料架类型"] == type);
  });
  ctx.body = {
    data: data,
    code: 200,
    msg: 'success'
  }
});

router.post('/getMaterialRack', async (ctx, next) => {
  const {
    form
  } = ctx.request.body;
  const materialList = readFile().filter(item => {
    for (const obj of form.list) {
      if ((obj['material'] == item['料盘'] && item['料架类型'] == form.materialRack) || (item['料盘'].slice(2,4) =='08' && item['料架类型'] == form.materialRack)) {
        return true;
      }
    }
  });
  const dataList = [];
  const allList = [];
  const typeSet = new Set();
  for (let i = 0; i < form.list.length; i++) {
    let str = form.list[i]['material'].slice(0, 2);
    let typeObj={
      material: str,
      materialRack:0
    };
    typeSet.add(JSON.stringify(typeObj));
    for (let k = 0; k < materialList.length; k++) {
      if (form.list[i]['material'] == materialList[k]['料盘']) {
        dataList.push(computed(form.list[i], materialList[k]));
      }
    };
  };
  const typeList = Array.from(typeSet).map(item => JSON.parse(item));
  for (const key of typeList.keys()) {
    let materialRack = 0;
    let materialLayer = 0;
    let layer = 0;
    let index = -1;
    for (let i = 0; i < dataList.length; i++) {
      if(dataList[i]['material'] == typeList[key]['material'] + '08'){
        index = i;
      }
      if(typeList[key]['material'] == dataList[i]['material'].slice(0,2)){
        layer =  dataList[i]['layer'];
        materialRack += dataList[i]['materialRack'];
        materialLayer += dataList[i]['materialLayer'];
      }
    };
    let materialRackAll = materialRack + Math.ceil(materialLayer / layer);
    
    if(materialLayer % layer != 0){
      let diffLayer = (materialRackAll * layer) - (materialLayer + (materialRack * layer));
      
      if(index != -1){
        dataList[index]['supplyNum'] += diffLayer * dataList[index]['单层数量'];
        dataList[index]['diff'] = dataList[index]['supplyNum'] - dataList[index]['demandNum'];
        index = -1;
      }else{
        let diffMaterial = materialList.filter(item => {
          return item['料盘'] == typeList[key]['material']+'08';
        })[0];
        let diffObj = {
          material: typeList[key]['material']+'08',
          demandNum:0,
          supplyNum:diffLayer * diffMaterial['单层数量'],
          diff:diffLayer * diffMaterial['单层数量'],
          ...diffMaterial,
          materialRack:0,
          materialLayer:diffLayer,
        };
        dataList.push(diffObj);
      }
    }
    let obj = {
      material: typeList[key]['material'],
      materialRack: materialRackAll,
    };
    allList.push(obj);
  }

  ctx.body = {
    data: [...dataList,...allList],
    code: 200,
    msg: 'success'
  }
});

router.post('/upload', async (ctx) => {
  const files = ctx.request.files; // 获取上传的文件
  const file = files.file; // 假设上传的文件字段名为 'file'

  if (file.originalFilename.split('.')[1] != 'xlsx' && file.originalFilename.split('.')[1] != 'xls' && file.originalFilename.split('.')[1] != 'csv') {
    ctx.body = {
      code: 400,
      msg: '上传文件失败'
    };
    return;
  }
  const targetPath = path.join(path.join(__dirname, '../public/files'), file.originalFilename);
  fs.renameSync(file.filepath, targetPath);
  writeFile(targetPath,path.join(__dirname, '../public/files/料架计算表格.json'));
  ctx.body = {
    code: 200,
    msg: '上传文件成功',
    data: {
      filename: file.originalFilename,
      path: "/files/"+file.originalFilename
    }
  };
});
function computed(demand, supply) {
  let obj = {
    material: demand['material'],
    materialRack: 0,
    materialLayer: 0,
    supplyNum: 0,
    demandNum: Number(demand.num),
    layer: supply['层数'],
    ...supply
  };
  if (demand.num >= supply['总数']) {
    obj.materialRack = Math.floor(demand.num / supply['总数']);
  };
  obj.materialLayer = Math.ceil((demand.num - (supply['总数'] * obj.materialRack)) / supply['单层数量']);
  if(obj.materialLayer == supply['层数']){
    obj.materialRack += 1;
    obj.materialLayer = 0;
  }
  obj.supplyNum = (supply['总数'] * obj.materialRack) + (supply['单层数量'] * obj.materialLayer);
  obj.diff = obj.supplyNum - obj.demandNum;
  return obj;
}

module.exports = router